const { messageApi, wxUserApi, API_CONFIG } = require('../../../utils/api');
const ws = require('../../../utils/ws');

// 统一内容解析：识别图片/文件/文本
function normalizeText(s) {
  try { return String(s).replace(/\r\n|\r|\n/g, ' ').replace(/\s{2,}/g, ' ').trim(); } catch (_) { return s || ''; }
}
function parseContent(s) {
  try {
    const str = String(s || '').trim();
    const base = str.split('?')[0].split('#')[0].trim();
    const ext = base.includes('.') ? base.split('.').pop().toLowerCase() : '';
    const imgExts = ['png','jpg','jpeg','gif','webp','bmp','svg'];
    const fileExts = ['doc','docx','pdf','ppt','pptx','xls','xlsx','txt','zip'];
    if (imgExts.includes(ext)) return { type: 'image', url: str };
    if (fileExts.includes(ext)) {
      const name = base.substring(base.lastIndexOf('/')+1) || '文件';
      return { type: 'file', url: str, name };
    }
    return { type: 'text', content: normalizeText(str) };
  } catch (_) {
    return { type: 'text', content: s || '' };
  }
}

Page({
  data: {
    peerId: null,
    peerName: '',
    peerAvatar: '/assets/联系人.png',
    messages: [],
    inputContent: '',
    anchorId: 'bottom',
    statusBarHeight: 0,
    // 底部工具面板 & 历史记录
    showToolbox: false,
    showHistory: false,
    historyKeyword: '',
    historyDate: ''
  },
  onLoad: function(options) {
    const peerId = Number(options.peerId || 0);
    const peerName = decodeURIComponent(options.peerName || '') || '会话';
    let sbh = 0;
    try {
      const info = wx.getSystemInfoSync();
      sbh = Number(info.statusBarHeight || 0) || 0;
    } catch (_) {}
    this.setData({ peerId, peerName, statusBarHeight: sbh });

    // 拉取学生头像（根据会话对象ID）
    if (peerId) {
      try {
        const normalize = (u) => {
          try {
            if (!u || typeof u !== 'string') return '/assets/联系人.png';
            const s = u.trim();
            if (!s || s === 'null' || s === 'undefined') return '/assets/联系人.png';
            if (s.startsWith('http://') || s.startsWith('https://') || s.startsWith('/')) return s;
            return '/assets/联系人.png';
          } catch (_) { return '/assets/联系人.png'; }
        };
        wxUserApi.getAvatarById(peerId).then(url => {
          this.setData({ peerAvatar: normalize(url) });
        }).catch(() => {
          this.setData({ peerAvatar: '/assets/联系人.png' });
        });
      } catch (_) {}
    }
    wx.setNavigationBarTitle({ title: `与${peerName}聊天` });
    this.initWS();
    this.loadHistory();
  },
  onShow: function() {
    try {
      const uid = Number(wx.getStorageSync('userId') || 1);
      if (!ws.isOpen) {
        ws.connect({ url: 'ws://localhost:1003/ws/chat', userId: uid, userType: 2 });
      }
    } catch (_) {}
  },
  onUnload: function() {
    // 仅移除当前页面的监听，保留全局WS连接，避免其他页面收不到推送
    try { if (this._wsHandler) { ws.removeListener(this._wsHandler); } } catch (_) {}
  },
  // 头像加载失败时回退为本地默认图
  onPeerAvatarError: function() {
    try {
      this.setData({ peerAvatar: '/assets/联系人.png' });
    } catch (_) {}
  },
  onBack: function() {
    wx.navigateBack({ fail: () => wx.redirectTo({ url: '/pages/messages/index' }) });
  },
  initWS: function() {
    try {
      const uid = Number(wx.getStorageSync('userId') || 1);
      ws.connect({ url: 'ws://localhost:1003/ws/chat', userId: uid, userType: 2 });
      // 确保不会重复注册监听
      if (this._wsHandler) { try { ws.removeListener(this._wsHandler); } catch (_) {} }
      this._wsHandler = (data) => {
        if (typeof data === 'string' && data === 'PING') return;
        const sid = Number((data && (data.senderId || data.fromId)) || 0);
        const rid = Number((data && (data.receiverId || data.toId)) || 0);
        const peerId = Number(this.data.peerId) || 0;
        const isMineTarget = rid === uid || !rid;
        const isPeer = sid === peerId;
        if (isMineTarget && isPeer && data && data.content) {
          const raw = normalizeText(data.content || '');
          const bubble = parseBubble(raw, false, '刚刚');
          this.setData({ messages: [...this.data.messages, bubble] }, () => this.scrollToBottom());
        }
        this.loadHistory();
      };
      ws.onMessage(this._wsHandler);
    } catch (e) {
      console.warn('教师端WS连接失败', e);
    }
    function parseBubble(content, mine, time) {
      const parsed = parseContent(content);
      return { id: Date.now(), ...parsed, time, mine };
    }
  },
  loadHistory: function() {
    try {
      const myId = Number(wx.getStorageSync('userId') || 1);
      const peerId = Number(this.data.peerId) || 0;
      Promise.all([
        messageApi.list(myId, 2),       // 我（老师）的收件箱：学生->老师
        peerId ? messageApi.list(peerId, 1) : Promise.resolve([]) // 学生的收件箱：老师->学生（我发出的）
      ]).then(([incomingList, peerInboxList]) => {
        try {
          const unreadIds = (Array.isArray(incomingList) ? incomingList : [])
            .filter(m => Number(m.senderId) === peerId && (m.isRead !== 1))
            .map(m => m.id)
            .filter(Boolean);
          if (unreadIds.length) {
            Promise.all(unreadIds.map(id => messageApi.markRead(id).catch(() => true))).catch(() => {});
          }
        } catch (_) {}
        const incoming = (Array.isArray(incomingList) ? incomingList : [])
          .filter(m => Number(m.senderId) === peerId)
          .map(m => {
            const c = norm(m.content);
            const parsed = parseContent(c);
            return { id: m.id, ...parsed, time: fmt(m.sendTime || m.time), t: ts(m.sendTime || m.time), mine: false };
          });
        const outgoing = (Array.isArray(peerInboxList) ? peerInboxList : [])
          .filter(m => Number(m.senderId) === myId && Number(m.receiverId) === peerId)
          .map(m => {
            const c = norm(m.content);
            const parsed = parseContent(c);
            return { id: m.id, ...parsed, time: fmt(m.sendTime || m.time), t: ts(m.sendTime || m.time), mine: true };
          });
        const merged = [...incoming, ...outgoing].sort((a, b) => (a.t - b.t));
        this.setData({ messages: merged.map(({t, ...rest}) => rest) }, () => this.scrollToBottom());
      }).catch((err) => {
        console.error('教师端加载会话历史失败', err);
      });
    } catch (e) {
      console.error('教师端读取用户信息失败', e);
    }
    function fmt(t) {
      try { const d = new Date(typeof t === 'number' ? t : (t || new Date())); const hh = String(d.getHours()).padStart(2, '0'); const mm = String(d.getMinutes()).padStart(2, '0'); return `${hh}:${mm}`; } catch (_) { return '刚刚'; }
    }
    function ts(t) {
      try { const d = new Date(typeof t === 'number' ? t : (t || new Date())); return d.getTime(); } catch (_) { return Date.now(); }
    }
    function norm(s) { return normalizeText(s); }
  },
  scrollToBottom: function() {
    this.setData({ anchorId: 'bottom' });
  },
  // 面板：由“更多”按钮控制展开/收起
  openMore: function() {
    const next = !this.data.showToolbox;
    this.setData({ showToolbox: next }, () => { if (next) this.scrollToBottom(); });
  },
  onInput: function(e) {
    this.setData({ inputContent: e.detail.value || '' });
  },
  previewImage: function(e) {
    const url = (e && e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.url) || '';
    if (!url) return;
    const imgs = (this.data.messages || []).filter(m => m.type === 'image').map(m => m.url).filter(Boolean);
    const current = url;
    wx.previewImage({ current, urls: imgs.length ? imgs : [url] });
  },
  openFile: function(e) {
    const url = (e && e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.url) || '';
    const name = (e && e.currentTarget && e.currentTarget.dataset && e.currentTarget.dataset.name) || '文档';
    if (!url) return;
    wx.showLoading({ title: '打开中...' });
    wx.downloadFile({
      url,
      success: (res) => {
        const temp = res.tempFilePath;
        if (res.statusCode === 200 && temp) {
          wx.openDocument({
            filePath: temp,
            showMenu: true,
            success: () => { wx.hideLoading(); },
            fail: () => {
              wx.hideLoading();
              try { wx.setClipboardData({ data: url }); } catch (_) {}
              wx.showToast({ title: '已复制链接，可外部打开', icon: 'none' });
            }
          });
        } else {
          wx.hideLoading();
          try { wx.setClipboardData({ data: url }); } catch (_) {}
          wx.showToast({ title: '下载失败，已复制链接', icon: 'none' });
        }
      },
      fail: () => {
        wx.hideLoading();
        try { wx.setClipboardData({ data: url }); } catch (_) {}
        wx.showToast({ title: '无法下载，已复制链接', icon: 'none' });
      }
    });
  },
  onSend: function() {
    const content = normalizeText(this.data.inputContent || '');
    if (!content) { wx.showToast({ title: '请输入消息', icon: 'none' }); return; }
    const receiverId = Number(this.data.peerId);
    wx.showLoading({ title: '发送中...' });
    try {
      const senderId = Number(wx.getStorageSync('userId') || 1);
      messageApi.send({ senderId, senderType: 2, receiverId, receiverType: 1, content }).then(() => {
        wx.hideLoading();
        this.setData({ inputContent: '' });
        const parsed = parseContent(content);
        const bubble = { id: Date.now(), ...parsed, time: '刚刚', mine: true };
        this.setData({ messages: [...this.data.messages, bubble] }, () => this.scrollToBottom());
      }).catch((err) => {
        wx.hideLoading();
        console.error('发送失败', err);
        wx.showToast({ title: '发送失败', icon: 'none' });
      });
    } catch (e) {
      wx.hideLoading();
      console.error('读取用户信息失败', e);
      wx.showToast({ title: '发送失败', icon: 'none' });
    }
  },
  // 选择相册图片并上传
  chooseImageFromAlbum: function() {
    const receiverId = Number(this.data.peerId);
    const senderId = Number(wx.getStorageSync('userId') || 1);
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album']
    }).then(res => {
      const filePath = (res.tempFilePaths && res.tempFilePaths[0]) || '';
      if (!filePath) return;
      wx.showLoading({ title: '上传中...' });
      wx.uploadFile({
        url: API_CONFIG.BASE_URL + '/tea/file/upload',
        filePath,
        name: 'file',
        formData: { folder: 'chat', userId: senderId },
        success: (r) => {
          try {
            const data = typeof r.data === 'string' ? JSON.parse(r.data) : (r.data || {});
            const fileUrl = data && (data.fileUrl || data.url || (data.data && data.data.fileUrl));
            if (!fileUrl) throw new Error('未获取到文件地址');
            this._sendImageMessage(String(fileUrl), senderId, receiverId);
          } catch (err) {
            console.error('解析上传结果失败', err);
            wx.showToast({ title: '上传失败', icon: 'none' });
          }
        },
        fail: (err) => {
          console.error('上传失败', err);
          wx.showToast({ title: '上传失败', icon: 'none' });
        },
        complete: () => { wx.hideLoading(); }
      });
    }).catch(() => {});
  },
  // 选择文件并上传
  chooseFile: function() {
    const receiverId = Number(this.data.peerId);
    const senderId = Number(wx.getStorageSync('userId') || 1);
    wx.chooseMessageFile({ count: 1, type: 'file' }).then(res => {
      const f = (res.tempFiles && res.tempFiles[0]) || null;
      if (!f || !f.path) return;
      wx.showLoading({ title: '上传中...' });
      wx.uploadFile({
        url: API_CONFIG.BASE_URL + '/tea/file/upload',
        filePath: f.path,
        name: 'file',
        formData: { folder: 'chat', userId: senderId },
        success: (r) => {
          try {
            const data = typeof r.data === 'string' ? JSON.parse(r.data) : (r.data || {});
            const fileUrl = data && (data.fileUrl || data.url || (data.data && data.data.fileUrl));
            if (!fileUrl) throw new Error('未获取到文件地址');
            const name = f.name || (String(fileUrl).split('/').pop()) || '文件';
            this._sendFileMessage(String(fileUrl), name, senderId, receiverId);
          } catch (err) {
            console.error('解析上传结果失败', err);
            wx.showToast({ title: '上传失败', icon: 'none' });
          }
        },
        fail: (err) => {
          console.error('上传失败', err);
          wx.showToast({ title: '上传失败', icon: 'none' });
        },
        complete: () => { wx.hideLoading(); }
      });
    }).catch(() => {});
  },
  _sendImageMessage: function(url, senderId, receiverId) {
    const content = String(url);
    messageApi.send({ senderId, senderType: 2, receiverId, receiverType: 1, content }).then(() => {
      const bubble = { id: Date.now(), type: 'image', url, time: '刚刚', mine: true };
      this.setData({ messages: [...this.data.messages, bubble], showToolbox: false }, () => this.scrollToBottom());
    }).catch(() => wx.showToast({ title: '发送失败', icon: 'none' }));
  },
  _sendFileMessage: function(url, name, senderId, receiverId) {
    const content = String(url);
    messageApi.send({ senderId, senderType: 2, receiverId, receiverType: 1, content }).then(() => {
      const bubble = { id: Date.now(), type: 'file', url, name, time: '刚刚', mine: true };
      this.setData({ messages: [...this.data.messages, bubble], showToolbox: false }, () => this.scrollToBottom());
    }).catch(() => wx.showToast({ title: '发送失败', icon: 'none' }));
  },
  // 历史记录面板
  openHistory: function() { this.setData({ showHistory: true, showToolbox: false }); },
  closeHistory: function() { this.setData({ showHistory: false }); },
  onHistoryDateChange: function(e) { this.setData({ historyDate: e.detail.value || '' }); },
  onHistorySearchInput: function(e) { this.setData({ historyKeyword: e.detail.value || '' }); },
  clearChat: function() {
    wx.showModal({ title: '清空聊天记录', content: '仅清除本地展示，不影响服务器数据', confirmText: '清空', cancelText: '取消' }).then(res => {
      if (res.confirm) { this.setData({ messages: [], showToolbox: false }); }
    }).catch(() => {});
  }
});